import os
import stripe
from datetime import datetime
from flask import Flask, render_template, jsonify, request, make_response, send_from_directory
from . import app

stripe.api_key = os.environ['STRIPE_SECRET']

@app.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
    donate_amount = int(request.json['amount'])
    donate_currency = request.json['currency'].lower()

    payment_types = []
    if donate_currency == 'cny':
        payment_types = ['alipay']
    elif donate_currency == 'eur':
        payment_types = ['sofort', 'ideal', 'sepa_debit', 'card']
    else:
        donate_currency = 'usd'
        payment_types = ['card', 'alipay']

    if donate_amount < 5:
        return make_response( 'Invalid Amount', 400 )

    session = stripe.checkout.Session.create(
        submit_type='donate',
        payment_method_types=payment_types,
        line_items=[{
            'price_data': {
            'currency': str(donate_currency).lower(),
            'product_data': {
                'name': 'KiCad Development Unit',
            },
            'unit_amount': 100,
            },
            'quantity': donate_amount,
        }],
        mode='payment',
        success_url='https://go.kicad.org/thank-you',
        cancel_url='https://go.kicad.org/donate',

    )

    return jsonify(id=session.id)

@app.route("/", host='donate.kicad.org')
def home():
    response = make_response(render_template("donate.html"))
    response.headers['Content-Security-Policy'] = "frame-ancestors 'self' https://kicad.org https://*.kicad.org;"
    return response

@app.route("/", host='download.kicad.org')
def checkout():
    response = make_response(render_template("download.html"))
    response.headers['Content-Security-Policy'] = "frame-ancestors 'self' https://kicad.org https://*.kicad.org;"
    return response

@app.route("/.well-known/apple-developer-merchantid-domain-association")
def get_data():
    return app.send_static_file("apple.txt")

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static', 'favicons'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')